/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.redis.utils.RedisUtils;
import com.comac.ins.isfd.constant.RedisConstants;
import com.comac.ins.isfd.constant.enums.IsfdStructureDefinitionTreeLevelEnum;
import com.comac.ins.isfd.constant.enums.IsfdStructureDefinitionTreeTaskDefaultEnum;
import com.comac.ins.isfd.constant.enums.IsfdStructureDefinitionTreeTypeEnum;
import com.comac.ins.isfd.constant.enums.PartFileTypeEnum;
import com.comac.ins.isfd.domain.*;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementStructureDefinitionTreeBo;
import com.comac.ins.isfd.domain.vo.*;
import com.comac.ins.isfd.mapper.*;
import com.comac.ins.isfd.service.IIsfdModelManagementStructureDefinitionTreeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 【模型库结构定义树】Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class IsfdModelManagementStructureDefinitionTreeServiceImpl implements IIsfdModelManagementStructureDefinitionTreeService {

    @Autowired
    private IsfdModelManagementStructureDefinitionTreeMapper baseMapper;

    @Autowired
    private IsfdModelManagementPartMapper isfdModelManagementPartMapper;

    @Autowired
    private IsfdModelManagementNecessaryItemsMapper isfdModelManagementNecessaryItemsMapper;

    @Autowired
    private IsfdModelManagementBoundaryMapper isfdModelManagementBoundaryMapper;

    @Autowired
    private IsfdModelManagementLoadMapper isfdModelManagementLoadMapper;

    @Autowired
    private IsfdModelManagementTaskMapper isfdModelManagementTaskMapper;

    @Autowired
    private IsfdModelManagementTaskRefPartMapper isfdModelManagementTaskRefPartMapper;

    /**
     * 查询【模型库结构定义树】
     *
     * @param id 主键
     * @return 【模型库结构定义树】
     */
    @Override
    public IsfdModelManagementStructureDefinitionTreeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询【模型库结构定义树】列表-平铺结构
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 【模型库结构定义树】分页列表
     */
    @Override
    public TableDataInfo<IsfdModelManagementStructureDefinitionTreeVo> queryPageList(IsfdModelManagementStructureDefinitionTreeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IsfdModelManagementStructureDefinitionTree> lqw = buildQueryWrapper(bo);
        Page<IsfdModelManagementStructureDefinitionTreeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询【模型库结构定义树】列表-树结构
     *
     * @return 【模型库结构定义树】分页列表
     */
    @Override
    public List<IsfdModelManagementStructureDefinitionTreeNodeVo> queryListTree() {
        List<IsfdModelManagementStructureDefinitionTree> isfdModelManagementStructureDefinitionTrees = baseMapper.selectList();

        List<IsfdModelManagementStructureDefinitionTreeNodeVo> treeVo = new ArrayList<>();
        isfdModelManagementStructureDefinitionTrees.forEach(isfdModelManagementStructureDefinitionTree -> {
            if (isfdModelManagementStructureDefinitionTree.getParentId() == 0) {
                IsfdModelManagementStructureDefinitionTreeNodeVo nodeVo = new IsfdModelManagementStructureDefinitionTreeNodeVo();
                BeanUtil.copyProperties(isfdModelManagementStructureDefinitionTree, nodeVo);
                treeVo.add(nodeVo);
            }
        });
        //最大等级
        Integer maxLevel = isfdModelManagementStructureDefinitionTrees.stream().max(Comparator.comparingInt(IsfdModelManagementStructureDefinitionTree::getLevel)).get().getLevel();
        //递归处理结构树
        this.handler(treeVo, isfdModelManagementStructureDefinitionTrees, 2, maxLevel);
        return treeVo;
    }

    public void handler(List<IsfdModelManagementStructureDefinitionTreeNodeVo> treeVo, List<IsfdModelManagementStructureDefinitionTree> isfdModelManagementStructureDefinitionTrees, Integer level, Integer maxLevel) {
        isfdModelManagementStructureDefinitionTrees.forEach(isfdModelManagementStructureDefinitionTree -> {
            treeVo.forEach(rootTree -> {
                if (rootTree.getId().equals(isfdModelManagementStructureDefinitionTree.getParentId())) {
                    IsfdModelManagementStructureDefinitionTreeNodeVo nodeVo = new IsfdModelManagementStructureDefinitionTreeNodeVo();
                    BeanUtil.copyProperties(isfdModelManagementStructureDefinitionTree, nodeVo);
                    if (rootTree.getChildren() == null) {
                        rootTree.setChildren(new ArrayList<>());
                    }
                    rootTree.getChildren().add(nodeVo);
                }
            });
        });
        treeVo.forEach(item -> {
            if (Objects.nonNull(item.getChildren()) && level < maxLevel) {
                this.handler(item.getChildren(), isfdModelManagementStructureDefinitionTrees, level + 1, maxLevel);
            }
        });
    }


    /**
     * 查询符合条件的【模型库结构定义树】列表
     *
     * @param bo 查询条件
     * @return 【模型库结构定义树】列表
     */
    @Override
    public List<IsfdModelManagementStructureDefinitionTreeVo> queryList(IsfdModelManagementStructureDefinitionTreeBo bo) {
        LambdaQueryWrapper<IsfdModelManagementStructureDefinitionTree> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdModelManagementStructureDefinitionTree> buildQueryWrapper(IsfdModelManagementStructureDefinitionTreeBo bo) {
        LambdaQueryWrapper<IsfdModelManagementStructureDefinitionTree> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, IsfdModelManagementStructureDefinitionTree::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), IsfdModelManagementStructureDefinitionTree::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getMark()), IsfdModelManagementStructureDefinitionTree::getMark, bo.getMark());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getLevel()), IsfdModelManagementStructureDefinitionTree::getLevel, bo.getLevel());
        lqw.eq(ObjectUtils.isNotEmpty(bo.getTaskDefault()), IsfdModelManagementStructureDefinitionTree::getTaskDefault, bo.getTaskDefault());
        return lqw;
    }

    /**
     * 新增【模型库结构定义树】
     *
     * @param bo 【模型库结构定义树】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdModelManagementStructureDefinitionTreeBo bo) {
        IsfdModelManagementStructureDefinitionTree add = MapstructUtils.convert(bo, IsfdModelManagementStructureDefinitionTree.class);
        QueryWrapper<IsfdModelManagementStructureDefinitionTree> qr = new QueryWrapper<>();
        qr.eq("mark", bo.getMark());
        qr.eq("parent_id", bo.getParentId());
        IsfdModelManagementStructureDefinitionTree node = baseMapper.selectOne(qr);
        if (bo.getMark().contains("::")) {
            throw new BaseException("节点标识：“" + bo.getMark() + "”不能包含特殊字符”::“");
        }
        if (node != null) {
            throw new BaseException("节点标识：“" + bo.getMark() + "”已存在");
        }
        validEntityBeforeSave(add);
        if (IsfdStructureDefinitionTreeLevelEnum.BATCH_NO.getValue().equals(bo.getLevel())) {
            add.setStructureType(IsfdStructureDefinitionTreeTypeEnum.LOGIC.getValue());
        } else {
            add.setStructureType(IsfdStructureDefinitionTreeTypeEnum.REAL.getValue());
        }
        String queryIndex = bo.getMark();
        if (bo.getParentId() != 0) {
            IsfdModelManagementStructureDefinitionTree isfdModelManagementStructureDefinitionTree = baseMapper.selectById(bo.getParentId());
            queryIndex = isfdModelManagementStructureDefinitionTree.getMark() + "::" + queryIndex;
            if (isfdModelManagementStructureDefinitionTree.getParentId() != 0) {
                isfdModelManagementStructureDefinitionTree = baseMapper.selectById(isfdModelManagementStructureDefinitionTree.getParentId());
                queryIndex = isfdModelManagementStructureDefinitionTree.getMark() + "::" + queryIndex;
            }
        }
        add.setQueryIndex(queryIndex);
        if (add.getTaskDefault() == null) {
            add.setTaskDefault(IsfdStructureDefinitionTreeTaskDefaultEnum.NOT_DEFAULT.getValue());
        }
        boolean flag = baseMapper.insert(add) > 0;
        return flag;
    }

    /**
     * 修改【模型库结构定义树】
     *
     * @param bo 【模型库结构定义树】
     * @return 是否修改成功
     */
    @Override
    @Transactional
    public Boolean updateByBo(IsfdModelManagementStructureDefinitionTreeBo bo) {
        IsfdModelManagementStructureDefinitionTree update = MapstructUtils.convert(bo, IsfdModelManagementStructureDefinitionTree.class);
        validEntityBeforeSave(update);
        int i = baseMapper.updateById(update);

        //删除redis中的数据
        IsfdModelManagementStructureDefinitionTree isfdModelManagementStructureDefinitionTree = baseMapper.selectById(update.getId());
        if (ObjectUtils.isNotEmpty(isfdModelManagementStructureDefinitionTree)) {
            String redisKey = RedisConstants.ISFD_MODEL_MANAGEMENT_STRUCTURE_DEFINITION_TREE_QUERY_INDEX + isfdModelManagementStructureDefinitionTree.getQueryIndex().replaceAll("::", ":");
            boolean deleted = RedisUtils.deleteObject(redisKey);
        }

        return i > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdModelManagementStructureDefinitionTree entity) {
        //TODO 做一些数据校验,如唯一约束

        //一个机型下只允许有一个默认批次
        Integer taskDefault = IsfdStructureDefinitionTreeTaskDefaultEnum.DEFAULT.getValue();
        if (IsfdStructureDefinitionTreeLevelEnum.BATCH_NO.getValue().equals(entity.getLevel()) && taskDefault.equals(entity.getTaskDefault())) {
            QueryWrapper<IsfdModelManagementStructureDefinitionTree> qr = new QueryWrapper<>();
            qr.eq("parent_id", entity.getParentId());
            qr.eq("task_default", taskDefault);
            IsfdModelManagementStructureDefinitionTree node = baseMapper.selectOne(qr);
            if (node != null) {
                throw new BaseException("保存失败，该机型下已存在模型组件时所用批次！");
            }
        }
    }

    /**
     * 校验并批量删除【模型库结构定义树】信息
     *
     * @return 是否删除成功
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(List<Long> ids) {
        String redisPrefix = RedisConstants.ISFD_MODEL_MANAGEMENT_STRUCTURE_DEFINITION_TREE_QUERY_INDEX;
        List<IsfdModelManagementStructureDefinitionTree> allTree = new ArrayList<>();
        ArrayList<String> queryIndexList = new ArrayList<>();
        IsfdModelManagementStructureDefinitionTree node = baseMapper.selectById(ids.get(0));
        allTree.add(node);
        queryIndexList.add(redisPrefix + node.getQueryIndex().replaceAll("::", ":"));
        if (node.getParentId() == 0) {
            QueryWrapper<IsfdModelManagementStructureDefinitionTree> qrChildren = new QueryWrapper<>();
            qrChildren.eq("parent_id", node.getId());
            List<IsfdModelManagementStructureDefinitionTree> childrenNode = baseMapper.selectList(qrChildren);
            for (IsfdModelManagementStructureDefinitionTree batchVo : childrenNode) {
                QueryWrapper<IsfdModelManagementStructureDefinitionTree> qrBatch = new QueryWrapper<>();
                qrBatch.eq("parent_id", batchVo.getId());
                List<IsfdModelManagementStructureDefinitionTree> sectionVoList = baseMapper.selectList(qrBatch);
                sectionVoList.forEach(childNode -> {
                    allTree.add(childNode);
                    queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
                });
            }
            childrenNode.forEach(childNode -> {
                allTree.add(childNode);
                queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
            });
        } else if (IsfdStructureDefinitionTreeLevelEnum.BATCH_NO.getValue().equals(node.getLevel())) {
            QueryWrapper<IsfdModelManagementStructureDefinitionTree> qrChildren = new QueryWrapper<>();
            qrChildren.eq("parent_id", node.getId());
            List<IsfdModelManagementStructureDefinitionTree> childrenNode = baseMapper.selectList(qrChildren);
            childrenNode.forEach(childNode -> {
                allTree.add(childNode);
                queryIndexList.add(redisPrefix + childNode.getQueryIndex().replaceAll("::", ":"));
            });
        }


        Integer level = node.getLevel();
        String queryIndex = node.getQueryIndex();
        String[] marks = queryIndex.split("::");
        // 构建 零件删除查询
        LambdaQueryWrapper<IsfdModelManagementPart> partLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> fileTypeList = new ArrayList<>();
        fileTypeList.add(PartFileTypeEnum.PART.getValue());
        fileTypeList.add(PartFileTypeEnum.FASTENER.getValue());
        partLambdaQueryWrapper.in(IsfdModelManagementPart::getFileType, fileTypeList);
        // 构建 组建件删除查询
        LambdaQueryWrapper<IsfdModelManagementTask> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建 必备件删除查询
        LambdaQueryWrapper<IsfdModelManagementNecessaryItems> necessaryItemsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建 边界条件删除查询
        LambdaQueryWrapper<IsfdModelManagementBoundary> boundaryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建 载荷文件删除查询
        LambdaQueryWrapper<IsfdModelManagementLoad> loadLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (IsfdStructureDefinitionTreeLevelEnum.MODEL.getValue().equals(level)) {
            String modelNumber = marks[0];
            isfdModelManagementPartMapper.delete(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber));
            isfdModelManagementTaskMapper.delete(taskLambdaQueryWrapper.eq(IsfdModelManagementTask::getModelNumber, modelNumber));
            isfdModelManagementNecessaryItemsMapper.delete(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber));
            isfdModelManagementBoundaryMapper.delete(boundaryLambdaQueryWrapper.eq(IsfdModelManagementBoundary::getModelNumber, modelNumber));
            isfdModelManagementLoadMapper.delete(loadLambdaQueryWrapper.eq(IsfdModelManagementLoad::getModelNumber, modelNumber));
        } else if (IsfdStructureDefinitionTreeLevelEnum.BATCH_NO.getValue().equals(level)) {
            String modelNumber = marks[0];
            String batchNumber = marks[1];
            isfdModelManagementPartMapper.delete(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber)
                .eq(IsfdModelManagementPart::getBatchNumber, batchNumber));
            isfdModelManagementTaskMapper.delete(taskLambdaQueryWrapper.eq(IsfdModelManagementTask::getModelNumber, modelNumber)
                .eq(IsfdModelManagementTask::getBatchNumber, batchNumber));
            isfdModelManagementNecessaryItemsMapper.delete(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber)
                .eq(IsfdModelManagementNecessaryItems::getBatchNumber, batchNumber));
            isfdModelManagementBoundaryMapper.delete(boundaryLambdaQueryWrapper.eq(IsfdModelManagementBoundary::getModelNumber, modelNumber)
                .eq(IsfdModelManagementBoundary::getBatchNumber, batchNumber));
            // 载荷文件 不关联 批次
        } else if (IsfdStructureDefinitionTreeLevelEnum.SECTION.getValue().equals(level)) {
            String modelNumber = marks[0];
            String batchNumber = marks[1];
            String sectionNumber = marks[2];
            List<IsfdModelManagementPartVo> partVoList = isfdModelManagementPartMapper.selectVoList(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber)
                .eq(IsfdModelManagementPart::getBatchNumber, batchNumber)
                .eq(IsfdModelManagementPart::getSectionNumber, sectionNumber));
            if (!CollectionUtils.isEmpty(partVoList)) {
                List<Long> partIds = partVoList.stream().map(IsfdModelManagementPartVo::getId).toList();
                List<IsfdModelManagementTaskRefPartVo> isfdModelManagementTaskRefPartVos = isfdModelManagementTaskRefPartMapper
                    .selectVoList(new LambdaQueryWrapper<IsfdModelManagementTaskRefPart>().in(IsfdModelManagementTaskRefPart::getPartId, partIds));
                if (!CollectionUtils.isEmpty(isfdModelManagementTaskRefPartVos)) {
                    List<Long> taskRefPartIds = isfdModelManagementTaskRefPartVos.stream().map(IsfdModelManagementTaskRefPartVo::getId).toList();
                    List<Long> taskIds = isfdModelManagementTaskRefPartVos.stream().map(IsfdModelManagementTaskRefPartVo::getTaskId).distinct().toList();
                    isfdModelManagementTaskRefPartMapper.deleteBatchIds(taskRefPartIds);
                    isfdModelManagementTaskMapper.deleteBatchIds(taskIds);
                }
                isfdModelManagementPartMapper.deleteBatchIds(partIds);
            }

            isfdModelManagementNecessaryItemsMapper.delete(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber)
                .eq(IsfdModelManagementNecessaryItems::getBatchNumber, batchNumber)
                .eq(IsfdModelManagementNecessaryItems::getSectionNumber, sectionNumber));
            // 载荷文件 和边界条件 不关联 部段
        } else {
            throw new BaseException("选择的构型定义不存在，请确认后重试！");
        }

        List<Long> allIds = allTree.stream().map(IsfdModelManagementStructureDefinitionTree::getId).collect(Collectors.toList());
        baseMapper.deleteBatchIds(allIds);
        //删除redis中的数据
        RedisUtils.deleteObject(queryIndexList);
        return Boolean.TRUE;
    }

    @Override
    public IsfdModelManagementStructureDefinitionTreeVo queryOneByQueryIndex(String modelNumber, String batchNumber, String sectionNumber) {
        String queryIndex = null;
        String redisKey = null;
        if (StringUtils.isBlank(modelNumber)) {
            throw new BaseException("机型编码不能为空。");
        }
        queryIndex = modelNumber;
        redisKey = RedisConstants.ISFD_MODEL_MANAGEMENT_STRUCTURE_DEFINITION_TREE_QUERY_INDEX + modelNumber;
        if (StringUtils.isNotBlank(batchNumber)) {
            queryIndex = queryIndex + "::" + batchNumber;
            redisKey = redisKey + ":" + batchNumber;
        }
        if (StringUtils.isNotBlank(sectionNumber)) {
            queryIndex = queryIndex + "::" + sectionNumber;
            redisKey = redisKey + ":" + sectionNumber;
        }
        // 两次try catch 的目的是不让redis报错影响流程
        try {
            IsfdModelManagementStructureDefinitionTreeVo treeVo = RedisUtils.getCacheObject(redisKey);
            if (treeVo != null) {
                return treeVo;
            }
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        // 从db拿
        IsfdModelManagementStructureDefinitionTreeVo treeVoFromDB = baseMapper.selectVoOne(new LambdaQueryWrapper<IsfdModelManagementStructureDefinitionTree>()
            .eq(IsfdModelManagementStructureDefinitionTree::getQueryIndex, queryIndex));

        try {
            // 放入redis
            RedisUtils.setCacheObject(redisKey, treeVoFromDB, Duration.ofDays(RedisConstants.QUERY_INDEX_EXPIRATION_DAY));
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        return treeVoFromDB;
    }

    @Override
    public IsfdModelManagementStructureDefinitionTreeVo queryDefaultBatch(String modelNumber) {
        IsfdModelManagementStructureDefinitionTreeVo modelVo = this.queryOneByQueryIndex(modelNumber, null, null);
        IsfdModelManagementStructureDefinitionTreeBo bo = new IsfdModelManagementStructureDefinitionTreeBo();
        bo.setParentId(modelVo.getId());
        bo.setTaskDefault(IsfdStructureDefinitionTreeTaskDefaultEnum.DEFAULT.getValue());
        List<IsfdModelManagementStructureDefinitionTreeVo> isfdModelManagementStructureDefinitionTreeVos = this.queryList(bo);
        if (CollectionUtils.isNotEmpty(isfdModelManagementStructureDefinitionTreeVos)) {
            return isfdModelManagementStructureDefinitionTreeVos.get(0);
        } else {
            throw new BaseException("该机型下未设置默认批次，请设置！");
        }
    }

    @Override
    public IsfdModelManagementStructureDefinitionTreeRemoveCheckVo removeCheck(Long id) {
        IsfdModelManagementStructureDefinitionTreeRemoveCheckVo result = new IsfdModelManagementStructureDefinitionTreeRemoveCheckVo();
        IsfdModelManagementStructureDefinitionTreeVo treeVo = baseMapper.selectVoById(id);
        if (treeVo == null) {
            throw new BaseException("选择的构型定义不存在，请确认后重试！");
        }

        Integer level = treeVo.getLevel();
        String queryIndex = treeVo.getQueryIndex();
        String[] marks = queryIndex.split("::");
        // 构建 零件查询
        LambdaQueryWrapper<IsfdModelManagementPart> partLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> fileTypeList = new ArrayList<>();
        fileTypeList.add(PartFileTypeEnum.PART.getValue());
        fileTypeList.add(PartFileTypeEnum.FASTENER.getValue());
        partLambdaQueryWrapper.in(IsfdModelManagementPart::getFileType, fileTypeList);
        // 构建 必备件查询
        LambdaQueryWrapper<IsfdModelManagementNecessaryItems> necessaryItemsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建 边界条件查询
        LambdaQueryWrapper<IsfdModelManagementBoundary> boundaryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构建 载荷文件查询查询
        LambdaQueryWrapper<IsfdModelManagementLoad> loadLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (IsfdStructureDefinitionTreeLevelEnum.MODEL.getValue().equals(level)) {
            String modelNumber = marks[0];
            result.setPartCount(isfdModelManagementPartMapper.selectCount(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber)));
            result.setNecessaryItemsCount(isfdModelManagementNecessaryItemsMapper.selectCount(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber)));
            result.setBoundaryCount(isfdModelManagementBoundaryMapper.selectCount(boundaryLambdaQueryWrapper.eq(IsfdModelManagementBoundary::getModelNumber, modelNumber)));
            result.setLoadCount(isfdModelManagementLoadMapper.selectCount(loadLambdaQueryWrapper.eq(IsfdModelManagementLoad::getModelNumber, modelNumber)));
        } else if (IsfdStructureDefinitionTreeLevelEnum.BATCH_NO.getValue().equals(level)) {
            String modelNumber = marks[0];
            String batchNumber = marks[1];
            result.setPartCount(isfdModelManagementPartMapper.selectCount(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber)
                .eq(IsfdModelManagementPart::getBatchNumber, batchNumber)));
            result.setNecessaryItemsCount(isfdModelManagementNecessaryItemsMapper.selectCount(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber)
                .eq(IsfdModelManagementNecessaryItems::getBatchNumber, batchNumber)));
            result.setBoundaryCount(isfdModelManagementBoundaryMapper.selectCount(boundaryLambdaQueryWrapper.eq(IsfdModelManagementBoundary::getModelNumber, modelNumber)
                .eq(IsfdModelManagementBoundary::getBatchNumber, batchNumber)));
            // 载荷文件 不关联 批次
            result.setLoadCount(0L);
        } else if (IsfdStructureDefinitionTreeLevelEnum.SECTION.getValue().equals(level)) {
            String modelNumber = marks[0];
            String batchNumber = marks[1];
            String sectionNumber = marks[2];
            result.setPartCount(isfdModelManagementPartMapper.selectCount(partLambdaQueryWrapper.eq(IsfdModelManagementPart::getModelNumber, modelNumber)
                .eq(IsfdModelManagementPart::getBatchNumber, batchNumber)
                .eq(IsfdModelManagementPart::getSectionNumber, sectionNumber)));
            result.setNecessaryItemsCount(isfdModelManagementNecessaryItemsMapper.selectCount(necessaryItemsLambdaQueryWrapper.eq(IsfdModelManagementNecessaryItems::getModelNumber, modelNumber)
                .eq(IsfdModelManagementNecessaryItems::getBatchNumber, batchNumber)
                .eq(IsfdModelManagementNecessaryItems::getSectionNumber, sectionNumber)));
            // 载荷文件 和边界条件 不关联 部段
            result.setLoadCount(0L);
            result.setBoundaryCount(0L);
        } else {
            throw new BaseException("选择的构型定义不存在，请确认后重试！");
        }

        return result;
    }


}
